package com.ruoyi.examation.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.examation.domain.ExamRegistration;
import com.ruoyi.examation.domain.ExamVenue;
import com.ruoyi.examation.vo.ExamRegistrationVo;
import com.ruoyi.examation.vo.ExamRegistrationUserVo;
import com.ruoyi.examation.mapper.ExamRegistrationMapper;
import com.ruoyi.examation.service.IExamRegistrationService;
import com.ruoyi.examation.service.IExamVenueService;
import com.ruoyi.examation.service.IExamScheduleService;
import com.ruoyi.examation.domain.ExamSchedule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 考试报名Service业务层处理
 *
 * @author Tellsea
 * @date 2025-09-28
 */
@Service
public class ExamRegistrationServiceImpl extends ServiceImpl<ExamRegistrationMapper, ExamRegistration> implements IExamRegistrationService {

    @Autowired
    private IExamVenueService examVenueService;

    @Autowired
    private IExamScheduleService examScheduleService;

    @Override
    public TableDataInfo<ExamRegistrationVo> queryList(ExamRegistrationVo entity) {
        return PageUtils.buildDataInfo(this.baseMapper.queryList(PageUtils.buildPage(), entity));
    }

    @Override
    public List<ExamRegistrationVo> queryAll(ExamRegistrationVo entity) {
        return this.baseMapper.queryList(entity);
    }

    @Override
    public ExamRegistrationVo queryById(Long id) {
        return this.baseMapper.queryById(id);
    }

    @Override
    public boolean registerExam(Long examId, Long venueId, Long userId) {
        // 检查是否已经报名
        ExamRegistration existingRegistration = this.lambdaQuery()
                .eq(ExamRegistration::getExamId, examId)
                .eq(ExamRegistration::getUserId, userId)
                .one();
        
        if (existingRegistration != null) {
            throw new ServiceException("用户已报名该考试");
        }
        
        // 检查考场容量
        ExamVenue venue = examVenueService.getById(venueId);
        if (venue == null) {
            throw new ServiceException("考场不存在");
        }
        
        // 获取当前考场的报名人数
        long currentRegistrationCount = this.lambdaQuery()
                .eq(ExamRegistration::getVenueId, venueId)
                .eq(ExamRegistration::getRegistrationStatus, "0") // 只统计已报名状态的记录
                .count();
        
        // 检查是否已满员
        if (currentRegistrationCount >= venue.getCapacity()) {
            throw new ServiceException("考场已满员，无法报名");
        }
        
        // 创建报名记录
        ExamRegistration registration = new ExamRegistration();
        registration.setExamId(examId);
        registration.setVenueId(venueId);
        registration.setUserId(userId);
        registration.setRegistrationTime(new Date());
        registration.setRegistrationStatus("0"); // 0已报名
        registration.setAttendanceStatus("0"); // 0未考试
        
        return this.save(registration);
    }

    @Override
    public List<ExamRegistrationUserVo> queryRegistrationUsers(Long examId, Long venueId) {
        return this.baseMapper.queryRegistrationUsers(examId, venueId);
    }

    @Override
    public List<ExamRegistrationUserVo> queryRegistrationUsersBySchedule(Long examId, Long scheduleId) {
        return this.baseMapper.queryRegistrationUsersBySchedule(examId, scheduleId);
    }

    @Override
    public TableDataInfo<ExamRegistrationUserVo> queryRegistrationUsersBySchedulePage(Long examId, Long scheduleId) {
        return PageUtils.buildDataInfo(this.baseMapper.queryRegistrationUsersBySchedulePage(PageUtils.buildPage(), examId, scheduleId));
    }

    @Override
    public boolean registerExamBySchedule(Long examId, Long scheduleId, Long userId) {
        // 检查是否已经在该门考试中报过名（不管是哪个时间段）
        ExamRegistration existingRegistration = this.lambdaQuery()
                .eq(ExamRegistration::getExamId, examId)
                .eq(ExamRegistration::getUserId, userId)
                .one();
        
        if (existingRegistration != null) {
            throw new ServiceException("您已报名该考试，无法重复报名");
        }
        
        // 检查考试时间段是否存在且启用
        ExamSchedule schedule = examScheduleService.getById(scheduleId);
        if (schedule == null) {
            throw new ServiceException("考试时间段不存在");
        }
        
        if (!"1".equals(schedule.getIsEnabled())) {
            throw new ServiceException("该考试时间段未启用");
        }
        
        // 检查考试时间段是否属于指定的考试
        // if (!examId.equals(schedule.getExamId())) {
        //     throw new ServiceException("考试时间段与考试不匹配");
        // }
        
        // 检查报名时间是否在有效期内
        // Date now = new Date();
        // if (schedule.getRegisterStartTime() != null && now.before(schedule.getRegisterStartTime())) {
        //     throw new ServiceException("报名尚未开始");
        // }
        
        // if (schedule.getRegisterEndTime() != null && now.after(schedule.getRegisterEndTime())) {
        //     throw new ServiceException("报名已结束");
        // }
        
        // 创建报名记录
        ExamRegistration registration = new ExamRegistration();
        registration.setExamId(examId);
        registration.setScheduleId(scheduleId);
        registration.setUserId(userId);
        registration.setRegistrationTime(new Date());
        registration.setRegistrationStatus("0"); // 0已报名
        registration.setAttendanceStatus("0"); // 0未考试
        
        return this.save(registration);
    }
}
